#include "ball.h"

#include "engine.h"
#include "paddle.h"
#include "score.h"

ball::ball(
	const char * image, 
	float * play_field, 
	paddle * player1, 
	score * score1,
	paddle * player2,
	score * score2)
{
     texture = load_bitmap(image);
     velocity[0] = 160.0f;
     velocity[1] = 160.0f;

     position[0] = 0.0f;
     position[1] = 0.0f;

     field[0] = play_field[0];
     field[1] = play_field[1];

	player[0] = player1;
	player[1] = player2;

	player_score[0] = score1;
	player_score[1] = score2;
}

ball::~ball()
{
     delete_bitmap(texture);
}

void ball::reset()
{
     position[0] = 0.0f;
     position[1] = 0.0f;
	velocity[0] *= -1.0f;
}

void ball::update(float time)
{
     position[0] += velocity[0] * time;
     position[1] += velocity[1] * time;

     if ((velocity[1] < 0 && position[1] < -field[1]) || 
	    (velocity[1] > 0 && position[1] > field[1])) {

          velocity[1] *= -1;
     }

     if (velocity[0] < 0 && player[0]->hit(position)) {

          velocity[0] *= -1;
     }

     if (velocity[0] > 0 && player[1]->hit(position)) {

          velocity[0] *= -1;
     }

	if (position[0] < -field[0]) {

		player_score[1]->add_point();
		reset();
	}

	if (position[0] > field[0]) {

		player_score[0]->add_point();
		reset();
	}
}

void ball::draw()
{
     float size[] = { 8.0f, 8.0f };
     draw_bitmap(texture, position, size);
}
